package com.digital.utils;

import io.jsonwebtoken.*;
import io.jsonwebtoken.security.Keys;
import io.jsonwebtoken.security.SecureDigestAlgorithm;

import javax.crypto.SecretKey;
import java.util.Date;
import java.util.Map;

public class JwtUtil
{
    /**
     * 生成jwt令牌
     * @param secretKey
     * @param ttlMillis
     * @param claims
     * @return
     */
    public static String createJWT(String secretKey, long ttlMillis, Map<String, Object> claims)
    {
        //指定算法
        SecureDigestAlgorithm<SecretKey, SecretKey> algorithm = Jwts.SIG.HS256;
        //有效时间
        long expMillis = System.currentTimeMillis()+ttlMillis;
        Date exp = new Date(expMillis);
        //生成秘钥
        SecretKey key = Keys.hmacShaKeyFor(secretKey.getBytes());
        String jwt = Jwts.builder()
                .signWith(key, algorithm)//指定秘钥
                .claims(claims)//设置负载
                .expiration(exp)//设置过期时间
                .compact();
        return jwt;
    }

    /**
     * 解析jwt令牌
     * @param token
     * @param secretKey
     * @return
     */
    public static Jws<Claims> parseJWT(String token,String secretKey)
    {
        //指定算法
        SecureDigestAlgorithm<SecretKey,SecretKey> algorithm = Jwts.SIG.HS256;
        //创建秘钥
        SecretKey key = Keys.hmacShaKeyFor(secretKey.getBytes());
        //解析token
        Jws<Claims> claimsJws = Jwts.parser()
                .verifyWith(key)
                .build()
                .parseSignedClaims(token);
        return claimsJws;
    }
}
